$(function() {
	//日期控件赋初值  |  默认首页和分组表最近时间
	initeDatetimepicker(2) ;
	var dateFrom = $('#'+tabId+' #sdate').val();

	//获取医师配置
	var doctors = doctorSetConfig;//全局变量里取
	$('#' + tabId + ' #searchsortlist').html();
	var Str = '<label><input type="checkbox" value="all" name="searchItem" id="selectAll">全部</label>'
			+ '<label  style="color:#4cbf3e;" ><input type="checkbox" value="hospname" name="searchItem">院区名称</label>'
			+ '<label><input type="checkbox" value="recordid" name="searchItem">就诊ID</label>'
			+ '<label><input type="checkbox" value="mr_no" name="searchItem">病案号</label>'
			+ '<label style="color:#4cbf3e;"><input type="checkbox"  value="pname" name="searchItem">姓名</label>';

	if (doctors[0] == 1) {
		Str += '<label  style="color:#4cbf3e;"><input type="checkbox" value="protomedicus" name="searchItem">主任医师</label>';
	}
	if (doctors[1] == 1) {
		Str += '<label  style="color:#4cbf3e;" ><input type="checkbox"  value="groupname" name="searchItem">主诊医师</label>';
	}
	if (doctors[2] == 1) {
		Str += '<label   style="color:#4cbf3e;" ><input type="checkbox"  value="physician" name="searchItem">主治医师</label>';
	}
	if (doctors[3] == 1) {
		Str += '<label   style="color:#4cbf3e;" ><input type="checkbox"  value="resident" name="searchItem">住院医师</label>';
	}
	Str += '<label  style="color:#4cbf3e;" ><input type="checkbox"  value="outdepname" name="searchItem">出院科室</label>';
    if(sysConfig.ICD_MATCH == "false") {
        Str += '<label  style="color:#4cbf3e;" ><input type="checkbox" value="dianame" name="searchItem">诊断名称</label>';
        Str += '<label  style="color:#4cbf3e;"><input type="checkbox"  value="opername" name="searchItem">手术名称</label>';
    }
    if(sysConfig.ICD_MATCH == "true") {
        Str += '<label  style="color:#4cbf3e;" ><input type="checkbox" value="diaCompare" name="searchItem">诊断名称对照</label>';
        Str += '<label  style="color:#4cbf3e;"><input type="checkbox"  value="operCompare" name="searchItem">手术名称对照</label>';
    }
	Str += '<label><input type="checkbox" value="pardrg_code" name="searchItem">DRG代码</label>';
	Str += '<label><input type="checkbox" value="adrg_code" name="searchItem">ADRG代码</label>';
	Str += '<label><input type="checkbox" value="mdc_code" name="searchItem">MDC代码</label>';
	$('#' + tabId + ' #searchsortlist').html(Str);
	nipicIndexSearch();
	var medData = diction.MED_INS_TYPE;// 医保类型选择的数据
	var medinsType='<option value="all">全部医保</option>';
	for(var i = 0;i<medData.length;i++){
		if(medData[i].DICVALUE){
			medinsType+='<option value="'+medData[i].DICVALUE+'">'+medData[i].DICDESC+'</option>';
		}
	}
	$('#' + tabId + ' #hcType').html(medinsType);
	$('#' + tabId + ' #searchBtn').on('click', function() {
        $('#' + tabId + ' #searchBox').addClass('sm');
        $('#' + tabId + ' #keyword').removeClass('input-lg');
        $('#' + tabId + ' #searchBtn').removeClass('btn-lg');
        $('#' + tabId + ' #searchsortlist').addClass('card-hide');
        
        loadCaseSearchResult(doctors);
    });
});
/**
 * @ Discription:加载数据
 * @Autor ：liuhongjun
 * @Date  ：2018年5月12日下午12:02:33
 */
function loadCaseSearchResult(doctors) {
	var colunms = [
			{
				"data" : "hospname",
				"title" : "院区名称"
			},
			{
				"data" : "hosplevel",
				"title" : "院区级别"
			},
			{
				"data" : "recordid",
				"title" : "就诊ID"
			},
			{
				"data" : "mr_no",
				"render" : function(obj, type, full) {
					var mrNo = full["mr_no"];
					var regPre = new RegExp('<span style="color:red">',"g");
					var reg = new RegExp('</span>',"g");
					//替换pname中的高亮部分，否则拼接a标签链接会有问题
					var pName=full["pname"]==undefined?"":full["pname"].replace(regPre,'').replace(reg,'');
					return "<a href=\"javascript:medicalRecord('" + full["pid"]
							+ "','" + pName + "')\">" + mrNo + "</a>";
				},
				"title" : "病案号"
			},{
				"data" : "isMedins",
				"title" : "是否医保病人",
				"render" : function(obj, type, full) {
					if(full["medinsType"]==null){
						return "非医保病人" ;
					}else{
						return "<span style='color: green;'>医保病人</span>" ;
					}
				}
			},{
				"data" : "medinsDesc",
				"title" : "医保类型"
			}, {
				"data" : "pname",
				"title" : "姓名"
			}, {
				"data" : "sex",
				"render" : function(obj, type, full) {
					var a = '1 ';
					var sex = $.trim(full.sex);
					if (sex == "1") {
						sex = "男";
					} else if (sex == "2") {
						sex = "女";
					} else {
						sex = "未知";
					}
					return sex;
				},
				"title" : "性别"
			}, {
				"data" : "age",
				"title" : "年龄"
			}, {
				"data" : "indate",
				"title" : "入院时间",
				"render" : function(obj, type, full) {
					var indate = full.indate;
					if (indate) {
						indate = indate.substr(0, 10);
					}
					return indate;
				},
			}, {
				"data" : "outdate",
				"title" : "出院时间",
				"render" : function(obj, type, full) {
					var outdate = full.outdate;
					if (outdate) {
						outdate = outdate.substr(0, 10);
					}
					return outdate;
				},

			}, {
				"data" : "outdepname",
				"title" : "出院科室"
			}, {
				"data" : "indays",
				"title" : "住院天数"
			}, {
				"data" : "costamount",
				"title" : "总费用",
				"render":function(obj,type,full){
					return formatNumber(full.costamount);
				}

			}];
	if(sysConfig.ICD_MATCH == "false") {
        colunms.push({
            "data" : "dianame",
            "width" : "80",
            "title" : "诊断名称"

        });
        colunms.push({
            "data" : "opername",
            "width" : "80",
            "title" : "手术名称"

        } );
    }
    if(sysConfig.ICD_MATCH == "true") {
        colunms.push({
            "data" : "diaCompare",
            "width" : "80",
            "title" : "诊断名称对照"

        });
        colunms.push({
            "data" : "operCompare",
            "width" : "80",
            "title" : "手术名称对照"

        });
    }
	if (doctors[0] == 1) {
		colunms.push({
			"data" : "protomedicus",
			"title" : "主任医师"
		});
	}
	if (doctors[1] == 1) {
		colunms.push({
			"data" : "groupname",
			"title" : "主诊医师"
		});
	}
	if (doctors[2] == 1) {
		colunms.push({
			"data" : "physician",
			"title" : "主治医师"
		});
	}
	if (doctors[3] == 1) {
		colunms.push({
			"data" : "resident",
			"title" : "住院医师"
		});
	}
	colunms.push({
		"data" : "pardrg_code",
		"title" : "DRG代码"
	}, {
		"data" : "drg_desc",
		"title" : "DRG名称"
	},{
		"data" : "adrg_code",
		"title" : "ADRG代码"
	}, {
		"data" : "adrg_desc",
		"title" : "ADRG名称"
	}, {
		"data" : "mdc_code",
		"title" : "MDC代码"
	}, {
		"data" : "mdc_desc",
		"title" : "MDC名称"
	}, {
		"data" : "total_weight",
		"type" : "numeric-comma",
		"title" : "权重",
		"render" : function(obj, type, full) {
			return formatNumber(full.total_weight);
		}
	}, {
		"data" : "avg_days",
		"title" : "平均住院日",
		"type" : "numeric-comma",
		"render" : function(obj, type, full) {
			return formatNumber(full.avg_days);
		}
	}, {
		"data" : "avg_fee",
		"type" : "numeric-comma",
		"render" : function(obj, type, full) {
			return formatNumber(full.avg_fee);
		},
		"title" : "次均费用"
	});
	var ajaxFunction = function(aoData, fnCallback, oSetting) {
		var matchingField = [];
		$('#' + tabId + ' [name="searchItem"]:checked').each(function(i, field){
			matchingField.push(field.value);
		});

		//正在加载

		var iDisplayStart = aoData.start;
		var iDisplayLength = aoData.length;
		$.ajax({
			"dataType" : 'json',
			"type" : "POST",
			"url" : contextPath + "/CaseGlobalSearch/getEsData.dhc",
			"data" : {
				'mrType' : $('#' + tabId + " #caseType").val(),
				'medinsType' : $('#' + tabId + " #hcType").val(),
				'matchingField' : matchingField.join(','),
				'keyword' : $('#' + tabId + " #keyword").val(),
				'hospCode' : paramTabPage[tabId].hospCode,
				'dateFrom' :$('#'+tabId+' #sdate').val(),
				'dateTo' : $('#'+tabId+' #edate').val(),
				'iDisplayStart' : iDisplayStart,//开始行数
				'pageSize' : iDisplayLength
			},
			"success" : function(result) {
				var data = [];
				console.log(result.data.caseData);
				if (result.success && result.data && result.data.caseData
						&& result.data.caseData.length > 0) {
					data.draw = aoData.draw;
					data.recordsTotal = result.data.caseTotalCount;
					data.recordsFiltered = result.data.caseTotalCount;
					data.data = result.data.caseData;
					drgUI.success("索引："+result.data.esindex+"<br>分组方案："+result.data.groupScheme+"<br> 分组器标杆及标杆年份："+result.data.asId);
					fnCallback(data, oSetting);
				}else if (result.success && result.data && result.data.caseData
						&& result.data.caseData.length == 0) {
					data.draw = 0;
					data.recordsTotal = 0;
					data.recordsFiltered = 0;
					data.data = {};
					fnCallback(data, oSetting);
					drgUI.warning("索引："+result.data.esindex+"<br>分组方案："+result.data.groupScheme+"<br>分组器标杆及标杆年份："+result.data.asId+"<br>无数据！");
				} else if(!result.success){
					data.draw = 0;
					data.recordsTotal = 0;
					data.recordsFiltered = 0;
					data.data = {};
					fnCallback(data, oSetting);
					drgUI.error(result.errorMessage);
				}else{
					data.draw = 0;
					data.recordsTotal = 0;
					data.recordsFiltered = 0;
					data.data = {};
					fnCallback(data, oSetting);
					drgUI.error("索引："+result.data.esindex+"<br>分组方案："+result.data.groupScheme+"<br> 分组器标杆及标杆年份："+result.data.asId+"<br>"+result.errorMessage);
				}
			
			}
		});
	};

	var paramsDataTables = {
		ajaxFunction : ajaxFunction,
		ordering : false,
		tableTitle : '病例明细',
		autoWidth : false,
		searching : false,
		orderCellsTop : true,
		scrollX : true,
		scrollY : '400px',
		pageLength : 100,
		fixedColumns:{'leftColumns' :7},
		lengthMenu : [ [ 10, 50, 100, 500, 1000],
				[ 10, 50, 100, 500, 1000] ],
		rowCallback : function(row, data, index) {
			var diaName = data.dianame;
			var operName = data.opername;
			var diaCompare = data.diaCompare;
			var operCompare = data.operCompare;
            if(sysConfig.ICD_MATCH == "false") {
                if (diaName) {
                    var diaNameStr='<div style="height: 50px; overflow-y: scroll;">';
                    var dataArray=diaName.split('θ');
                    diaNameStr+=dataArray.join("<br><span class='displayNone'>θ</span>");
                    diaNameStr+='</div>'
                    //先将span元素替换，否则有可能会被换行符分割，造成页面显示异常的问题，处理后再替换回来
                    // var regPre = new RegExp('<span style="color:red">',"g");
                    // var reg = new RegExp('</span>',"g");
                    // diaName=diaName.replace(regPre,'Ω').replace(reg,'θ');
                    // var regPreAfter = new RegExp('Ω',"g");
                    // var regAfter = new RegExp('θ',"g");
                    // diaNameStr=diaNameStr.replace(regPreAfter,'<span style="color:red">').replace(regAfter,'</span>');
                    $('td:eq(14)', row).html(diaNameStr);
                }
                if (operName) {
                    var operNameStr='<div style="height: 50px; overflow-y: scroll;">';
                    var dataArray=operName.split('θ');
                    operNameStr+=dataArray.join("<br><span class='displayNone'>θ</span>");
                    operNameStr+='</div>'
                    //先将span元素替换，否则有可能会被换行符分割，造成页面显示异常的问题，处理后再替换回来
                    // var regPre = new RegExp('<span style="color:red">',"g");
                    // var reg = new RegExp('</span>',"g");
                    // operName=operName.replace(regPre,'Ω').replace(reg,'θ');
                    // var regPreAfter = new RegExp('Ω',"g");
                    // var regAfter = new RegExp('θ',"g");
                    // operNameStr=operNameStr.replace(regPreAfter,'<span style="color:red">').replace(regAfter,'</span>');
                    $('td:eq(15)', row).html(operNameStr);
                }
            }
            if(sysConfig.ICD_MATCH == "true") {
                if (diaCompare) {
                    var diaCompareStr='<div style="height: 50px; overflow-y: scroll;">';
                    var dataArray=diaCompare.split('θ');
                    diaCompareStr+=dataArray.join("<br><span class='displayNone'>θ</span>");
                    diaCompareStr+='</div>'
                    //先将span元素替换，否则有可能会被换行符分割，造成页面显示异常的问题，处理后再替换回来
                    var regPre = new RegExp('<span style="color:red">',"g");
                    var reg = new RegExp('</span>',"g");
                    diaCompare=diaCompare.replace(regPre,'Ω').replace(reg,'θ');
                    var regPreAfter = new RegExp('Ω',"g");
                    var regAfter = new RegExp('θ',"g");
                    diaCompareStr=diaCompareStr.replace(regPreAfter,'<span style="color:red">').replace(regAfter,'</span>');
                    $('td:eq(14)', row).html(diaCompareStr);
                }
                if (operCompare) {
                    var operCompareStr='<div style="height: 50px; overflow-y: scroll;">';
                    var dataArray=operCompare.split('θ');
                    operCompareStr+=dataArray.join("<br><span class='displayNone'>θ</span>");
                    operCompareStr+='</div>'
                    //先将span元素替换，否则有可能会被换行符分割，造成页面显示异常的问题，处理后再替换回来
                    var regPre = new RegExp('<span style="color:red">',"g");
                    var reg = new RegExp('</span>',"g");
                    operCompare=operCompare.replace(regPre,'Ω').replace(reg,'θ');
                    var regPreAfter = new RegExp('Ω',"g");
                    var regAfter = new RegExp('θ',"g");
                    operCompareStr=operCompareStr.replace(regPreAfter,'<span style="color:red">').replace(regAfter,'</span>');
                    $('td:eq(15)', row).html(operCompareStr);
                }
            }
		}
	};
	$('#' + tabId + ' #caseListTable-sub').dataTableServerPaging(colunms, paramsDataTables);
}
/**
 * @ Discription:输入框的下拉框
 * @Autor ：liuhongjun
 * @Date  ：2018年5月12日下午12:01:21
 */
function nipicIndexSearch() {
	$('input').iCheck({
        checkboxClass: 'icheckbox_polaris',
        radioClass: 'iradio_square-blue',
        increaseArea: '-10%'
    });

	$('#selectAll').on('ifChecked', function(event){
        $('#searchsortlist input').iCheck('check');
    }).on('ifUnchecked', function(event){
        $('#searchsortlist input').iCheck('uncheck');
    });
	$("#keyword").focus(function() {
		$('#searchsortlist').removeClass('card-hide');
	});

	$('#'+ tabId +' #caseType').on('change',function(e){
		if(e.target.value==='hcCase'){
            $('#'+ tabId +' #hcTypeWrapper').addClass('slideRight');
		} else {
            $('#'+ tabId +' #hcTypeWrapper').removeClass('slideRight');
		}
	});

	$(document).click(function(evt) {
		if ($(evt.target).attr("id") == "searchsortlist" || $(evt.target).attr("id") == "keyword" || $(evt.target).closest(".searchItem").length > 0) {
			$('#searchsortlist').removeClass('card-hide');
		} else {
			$('#searchsortlist').addClass('card-hide');
		}
	});
}

/**
 * 初始化时间控件
 */
function initeDatetimepicker(startView) {
	// 定义延迟对象reportId
	var dtd = $.Deferred();
	if(!startView) {
		startView = 3 ;
	}
	// 日历设置及初始化
	$("#"+tabId+" #date_div").bind("mouseover", opc1);
	$("#"+tabId+' #date_div').bind('mouseout', opc0);
	$('#'+tabId+ " #sdate").datetimepicker({
	    format: "yyyy-mm-dd",
	    autoclose: true,
	    todayBtn: true,
	    minView: 2,
	    startView:startView,
	    language: 'zh-CN'
	});
	$('#'+tabId+" #edate").datetimepicker({
	    format: "yyyy-mm-dd",
	    autoclose: true,
	    todayBtn: true,
	    minView: 2,
	    startView:startView,
	    language: 'zh-CN',
	});
	$("#"+tabId+" #sdate").datetimepicker().on('show', function(ev){
		$('#'+tabId+' #date_div').unbind();
	});
	$("#"+tabId+" #sdate").datetimepicker().on('hide', function(ev){
		$('#'+tabId+' #date_div').bind('mouseover', opc1);
		$('#'+tabId+' #date_div').bind('mouseout', opc0);
	});
	$("#"+tabId+" #edate").datetimepicker().on('show', function(ev){
		$('#'+tabId+' #date_div').unbind();
	});
	$("#"+tabId+" #edate").datetimepicker().on('hide', function(ev){
		$('#'+tabId+' #date_div').bind('mouseover', opc1);
		$('#'+tabId+' #date_div').bind('mouseout', opc0);
	});
	
	$.ajax({
		url:contextPath + "/Report/initeDateTimePicker.dhc",
		async:false,
		type:"post",
		dataType:"json",
		success:function(data){
			var date = data.data
			// 获取该月份的开始日期和结束日期
			if(date) {
				var startDate=date.startDateMonth.substr(0,4)+'-01-01';
				$('#'+tabId+' #sdate').val(startDate);
				$('#'+tabId+' #edate').val(date.lastDate);
			}else{
				$('#'+tabId+' #sdate').val(GetDateStr(0,'d'));
				$('#'+tabId+' #edate').val(GetDateStr(0,'d'));
			}
			// 将延迟对象改为完成状态
			dtd.resolve();
		}
	})
	// 此时的dtd对象为 未完成状态
	return dtd.promise();
}